package com.ganzi.ganziserver.shiro.redis;


import java.util.concurrent.atomic.AtomicInteger;
import com.ganzi.ganziserver.core.User;
import com.ganzi.ganziserver.dao.UserDao;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * 登陆次数限制
 */
public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher {

    private static Logger logger = LoggerFactory.getLogger(MyShiroRealm.class);

    public static final String DEFAULT_RETRYLIMIT_CACHE_KEY_PREFIX = "shiro:cache:retrylimit:";
    private String keyPrefix = DEFAULT_RETRYLIMIT_CACHE_KEY_PREFIX;
    @Autowired
    private UserDao userdao;
    private RedisManager redisManager;

    public void setRedisManager(RedisManager redisManager) {
        this.redisManager = redisManager;
    }

    private String getRedisKickoutKey(String username) {
        return this.keyPrefix + username;
    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {

        String userName = (String) token.getPrincipal();
        //获取用户登录次数
        AtomicInteger retryCount = (AtomicInteger)redisManager.get(getRedisKickoutKey(userName));
        if (retryCount == null) {
            retryCount = new AtomicInteger(0);
        }
        if (retryCount.incrementAndGet() > 5) {
//            if (user != null && 0 == user.getLocked()){
//                //修改数据库的状态字段为锁定
//                user.setLocked(1);
//                try {
//                    userdao.updateUser(user);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//            logger.info("锁定用户" + username);
            throw new ExcessiveAttemptsException();
        }
        //判断用户账号和密码是否正确
        boolean matches = super.doCredentialsMatch(token, info);
        if (matches) {
            redisManager.del(getRedisKickoutKey(userName));
        }else{
            redisManager.set(getRedisKickoutKey(userName), retryCount,120);
        }
        //清除匹配的随机数
        try {
            User user = userdao.findUserByName(userName);
            if(user != null){
                user.setRandom("");
                userdao.updateUser(user);
            }
        } catch (Exception e) {
            logger.error("清除登录随机数失败："+e.getMessage());
        }
        return matches;
    }

    /**
     * 根据用户名 解锁用户
     * @param username
     * @return
     */
    public void unlockAccount(String username){
        try {
            User user = userdao.findUserByName(username);
            if (user != null){
                //修改数据库的状态字段为锁定
                user.setLocked(0);
                userdao.updateUser(user);
                redisManager.del(getRedisKickoutKey(username));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}